package Tailfile

import (
	"fmt"
	"logagent/common"
)

type tailTaskManger struct {
	tailTaskMap      map[string]*tailTask       // map path to instance
	collectEntryList []common.CollectEntry      //all config
	confChan         chan []common.CollectEntry //wait new config channel
}

var (
	ttManager *tailTaskManger
)

func TailInit(allConf []common.CollectEntry) (err error) {
	//create every log instance
	ttManager = &tailTaskManger{
		tailTaskMap:      make(map[string]*tailTask, 20),
		collectEntryList: allConf,
		confChan:         make(chan []common.CollectEntry),
	}
	for _, conf := range allConf {
		tt := newTailTask(conf.Path, conf.Topic)
		err = tt.Init()
		if err != nil {
			fmt.Printf("create tailobj for path: %s failed, err :%v\n", conf.Path, err)
			continue
		}
		ttManager.tailTaskMap[tt.path] = tt
		go tt.run()
	}

	go ttManager.watch()
	return
}

func (t *tailTaskManger) watch() {
	for {
		newConf := <-t.confChan
		fmt.Printf("get new conf from etcd, conf:%v,start new manger tailTask\n", newConf)
		//1.create new tailTask
		//2.it has tailTask,will continue to work
		//3. delete some tailTassk about old have and new don't have
		for _, conf := range newConf {
			if _, ok := t.tailTaskMap[conf.Path]; ok {
				continue
			}
			tt := newTailTask(conf.Path, conf.Topic)
			err := tt.Init()
			if err != nil {
				fmt.Printf("create tailobj for path: %s failed, err :%v\n", conf.Path, err)
				continue
			}
			t.tailTaskMap[tt.path] = tt
			go tt.run()
		}

		for key, task := range t.tailTaskMap {
			var found bool
			for _, conf := range newConf {
				if key == conf.Path {
					found = true
					break
				}
			}
			if !found {
				fmt.Printf("log path:%v is stop \n", key)
				delete(t.tailTaskMap, key)
				task.cancel()
			}
		}
	}

}

func SendNewConf(newConf []common.CollectEntry) {
	ttManager.confChan <- newConf
}
